import { ElMessageBox } from "element-plus";
import { defineStore } from "pinia";
import router from "../router";
import { useDaside } from "../store/Daside";
import { regionData, CodeToText } from "element-china-area-data-new";
export const useDheader = defineStore("useDheader", {
  persist: {
    key: "yyqs-Dheader",
    storage: sessionStorage,
    paths: ["header"],
  },
  state: () => {
    return {
      header: {
        width: 0,
        row1: {
          isFullScreen: false,
          isLanguageSwitch: true,
          activeTag: "schedule",
          login: {
            isLogin: true,
            identifyCode: "1234",
            loginMode: 1,
          },
          personalCenter: {
            ispersonalCenterDisplay: false,
            score: 0,
            isModify: false,
            //添加新标签输入框
            tag: {
              tagName: "",
              isInputDisplay: false,
            },
            localtionSelector: {
              options: regionData,
              props: {
                expandTrigger: "hover",
                //懒加载和搜索不能同时使用
                // lazy: true,
                // lazyLoad(
                //     node: { label: string; level: number },
                //     resolve: (arg0: { value: number; label: string; leaf: boolean }[]) => void
                // ) {
                //     const { label, level } = node;

                //     getData(label, level);
                //     setTimeout(() => {
                //         const nodes = Array.from({ length: data.length }).map((item, index) => ({
                //             value: data[index].value,
                //             label: data[index].label,
                //             leaf: level >= 2
                //         }));
                //         resolve(nodes);
                //     }, 1000);
                // }
              } as any,
              data: [] as any,
            },
            personal: {
              petName: "一叶千生",
              userName: "1",
              password: "123",
              sex: "1",
              work: "目前自由开发者",
              location: ["440000", "440400", "440402"],
              stack: "Vue3、Js/Ts、Php",
              tags: [
                { tagName: "宅", type: "success" },
                { tagName: "随心", type: "danger" },
                { tagName: "什么都想知道一点", type: "warning" },
                { tagName: "无为", type: "info" },
              ] as any,
            },
            personalForm: {} as any,
          },
          path: [] as any, //导航路径（面包屑风格）
          isFold: true,
        },
        row2: {
          isSubpageFullScreen: false,
          isRefresh: true,
          isRow2Display: true,
          tabs: [] as any, //标签页
          activateTab: "/home",
        },
      },
    };
  },
  getters: {
    getLocaltion(state) {
      return (
        CodeToText[state.header.row1.personalCenter.personal.location[0]] +
        "--" +
        CodeToText[state.header.row1.personalCenter.personal.location[1]] +
        "--" +
        CodeToText[state.header.row1.personalCenter.personal.location[2]]
      );
    },
  },
  actions: {
    //全屏操作，0、1分别代表页面全屏、main区域全屏
    initEvent() {
      //全屏事件
      document.addEventListener("keydown", (e: any) => {
        if (e.keyCode == 122) {
          e.preventDefault();
          this.fullScreen(0);
        }
      });
      document.addEventListener(
        "fullscreenchange",
        () => {
          if (document.fullscreenEnabled) {
            if (!document.fullscreenElement)
              this.header.row1.isFullScreen = false;
          }
        },
        true
      );

      //点击区域外隐藏菜单事件
      document.addEventListener("click", (event: any) => {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        if (!this.header.row1.isFold) {
          while (el) {
            if (["item1", "item2", "item3"].indexOf(el.id) > -1) {
              e.stopPropagation();
              return;
            }
            el = el.parentNode;
          }
          this.header.row1.isFold = true;
        }
      });

      //保存初始化宽度
      this.header.width = window.dom.id("Dheader").offsetWidth;
    },
    fullScreen(id: number) {
      if (document.fullscreenEnabled && id == 0) {
        document.fullscreenElement
          ? (() => {
              document.exitFullscreen();
              setTimeout(() => {
                this.header.row1.isFullScreen = false;
              }, 200);
            })()
          : (() => {
              document.documentElement.requestFullscreen();
              setTimeout(() => {
                this.header.row1.isFullScreen = true;
              }, 200);
            })();
      } else {
        this.header.row2.isSubpageFullScreen =
          !this.header.row2.isSubpageFullScreen;
        setTimeout(() => {
          this.header.width = window.dom.id("Dheader").offsetWidth;
        }, 1);
      }
    },
    /*
     *row1组件操作
     */
    //语言切换
    row1LanguageSwitch() {
      this.header.row1.isLanguageSwitch = !this.header.row1.isLanguageSwitch;

      this.header.row1.isLanguageSwitch
        ? (() => {
            ElMessage({
              message: "已切换中文！",
              type: "success",
              duration: 500,
            });
          })()
        : (() => {
            ElMessage({
              message: "已切换英文！",
              type: "success",
              duration: 500,
            });
          })();
    },
    //退出登录
    row1Logout() {
      ElMessageBox.confirm("是否登出", "警告", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
        showClose: false,
      })
        .then(() => {
          ElMessage({
            type: "success",
            message: "登出成功",
            duration: 500,
          });
          router.replace({ path: "/login" });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消登出",
            duration: 500,
          });
        });
    },
    //渲染修改信息组件，赋值表单
    row1Modify() {
      this.header.row1.personalCenter.personalForm = JSON.parse(
        JSON.stringify(this.header.row1.personalCenter.personal)
      );
      this.header.row1.personalCenter.isModify = true;
    },
    //保存修改信息，同步表单到个人数据
    row1SaveOrCancel(type: number) {
      type == 1
        ? (() => {
            this.header.row1.personalCenter.personal =
              this.header.row1.personalCenter.personalForm;
            ElNotification({
              title: "操作通知",
              duration: 500,
              type: "success",
              showClose: false,
              dangerouslyUseHTMLString: true,
              message: "<strong>修改成功</strong>",
            });
          })()
        : this.header.row1.personalCenter.isModify
        ? ElNotification({
            title: "操作通知",
            duration: 500,
            type: "info",
            showClose: false,
            dangerouslyUseHTMLString: true,
            message: "<strong>修改取消</strong>",
          })
        : "";
      this.header.row1.personalCenter.isModify = false;
    },
    //表单地址选择器搜索事件
    row1Search(node: any, key: String): boolean {
      if (node.text.indexOf(key) > -1) {
        return true;
      }
      return false;
    },

    //懒加载操作，不能和搜索同时使用
    // getData(label: string, level: number) {
    //     if (level == 0) {
    //         this.header.row1.personalCenter.localtionSelector.data =
    //             this.header.row1.personalCenter.localtionSelector.options;
    //     } else if (level == 1) {
    //         this.header.row1.personalCenter.localtionSelector.data =
    //             regionData[
    //                 regionData.findIndex((val: { label: string }) => val.label == label)
    //             ].children;
    //     } else {
    //         this.header.row1.personalCenter.localtionSelector.data =
    //             this.header.row1.personalCenter.localtionSelector.data[
    //                 this.header.row1.personalCenter.localtionSelector.data.findIndex(
    //                     (val: { label: string }) => val.label == label
    //                 )
    //             ].children;
    //     }
    // },

    //删除个性标签
    deleteTag(tag: string) {
      this.header.row1.personalCenter.personalForm.tags.splice(
        this.header.row1.personalCenter.personalForm.tags.indexOf(tag),
        1
      );
    },
    //添加个性标签
    addTag() {
      if (this.header.row1.personalCenter.tag.tagName) {
        this.header.row1.personalCenter.personalForm.tags.push({
          tagName: JSON.parse(
            JSON.stringify(this.header.row1.personalCenter.tag.tagName)
          ),
          type: ["success", "warning", "danger", "info"][
            Math.floor(Math.random() * 4)
          ],
        });
      }
      this.header.row1.personalCenter.tag.isInputDisplay = false;
      this.header.row1.personalCenter.tag.tagName = "";
    },
    //侧边导航栏显示/隐藏
    row1DasideDisplay() {
      const Daside = useDaside();

      if (Daside.aside.isCollapse && Daside.aside.Daside) {
        Daside.aside.isMask = true;
        Daside.aside.isDasideHide = false;
      }
      Daside.aside.isCollapse = !Daside.aside.isCollapse;

      //折叠菜单header宽度跟随变化
      //需要在变化后才能获取
      setTimeout(() => {
        this.header.width = window.dom.id("Dheader").offsetWidth;
      }, 400);
    },
    //侧边设置栏显示/隐藏
    row1SettingsDisplay() {
      const Daside = useDaside();
      Daside.aside.settings.isSettingsHide = false;
      Daside.aside.isMask = true;
    },

    /*
     *row2组件操作
     */
    Delete(index: number) {
      this.header.row2.tabs.splice(index, 1);
      index > 0
        ? router.push({ path: this.header.row2.tabs[index - 1].to })
        : router.push({ path: "/home" });
    },
    row2Command(command: string | number | object) {
      if (command == 1) {
        let index = this.header.row2.tabs.findIndex(
          (v: { to: string }) => v.to == router.currentRoute.value.path
        );
        this.Delete(index);
        ElMessage.success("已关闭当前标签页！");
      } else if (command == 3) {
        let index = this.header.row2.tabs.findIndex(
          (v: { to: string }) => v.to == router.currentRoute.value.path
        );
        index == -1
          ? (this.header.row2.tabs.length = 0)
          : (this.header.row2.tabs = this.header.row2.tabs.splice(index, 1));
        ElMessage.success("已关闭其他标签页！");
      } else if (command == 4) {
        this.header.row2.tabs.length = 0;
        router.replace({ path: "/home" });
        ElMessage.success("已关闭全部标签页！");
      }
    },
    row2DeleteTab(item: any) {
      let index = this.header.row2.tabs.indexOf(item);
      item.to == this.header.row2.activateTab
        ? this.Delete(index)
        : this.header.row2.tabs.splice(index, 1);
    },
    row2Refresh() {
      this.header.row2.isRefresh = false;
      let Refresh = window.dom.id("refresh");
      Refresh.style.cssText =
        "transform:rotate(360deg);transition: all 1s linear;";
      setTimeout(() => {
        Refresh.style.cssText = "";
        nextTick(() => {
          this.header.row2.isRefresh = true;
        });
      }, 1000);
    },
  },
});
